package com.cj.user.service.file;

import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/7/4 22:23
 */
public class UpLoad {

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    public JSONObject upload(MultipartFile file) throws IOException {
        // 获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        // 获取文件后缀
        String extension = FilenameUtils.getExtension(originalFilename);

        // 新的名称
        String newFilename = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) +
                UUID.randomUUID().toString().replace("-", "") + extension;

        // 获取文件大小
        long fileSize = file.getSize();

        // 获取文件类型
        String fileType = file.getContentType();

        // 根据日期生成目录
        String classpath = ResourceUtils.getURL("classpath").getPath() + "/static/files";
        String dateDirPath = classpath + "/" + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) {
            dateDir.mkdirs();
        }

        // 文件上传
        file.transferTo(new File(dateDir, newFilename));

        return new JSONObject();
    }
}
